package com.xsd.juc;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Description: 售票
 * @Author: zhoufuzong
 * @Created: 2020-12-27 18:26:37
 * @Version: 1.1.0
 */



class Ticket{     // 资源类

    private  int number=30;

    private Lock lock = new ReentrantLock();

    public  void saleTicket(){

        lock.lock();
        try {
            if (number>0){

                System.out.println(Thread.currentThread().getName()+"\t卖出第："+(number--)+"\t还剩下："+number);

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }


    }

}
/**
 * 题目： 三个售票员  卖出 30张票
 *
 * 多线程编程的企业级套路+模板
 *
 * 1        在高内聚低耦合的前提下，线程      操作( 对外暴露的调用方法)    资源类
 *          空调跟人 低耦合
 *          空调的制冷制热的方法高内聚在空调本身
 *
 */

public class SaleTicket {

    public static void main(String[] args) throws Exception {   // 一切程序的入口

        Ticket ticket = new Ticket();

        new Thread(()->{ for (int i = 0; i <=40 ; i++) {ticket.saleTicket();}},"A").start();
        new Thread(()->{ for (int i = 0; i <=40 ; i++) {ticket.saleTicket();}},"B").start();
        new Thread(()->{ for (int i = 0; i <=40 ; i++) {ticket.saleTicket();}},"C").start();



//        Thread(Runnable target, String name)

//        new Thread(new T(),"AA");

        // NEW RUNNABLE BLOCKED WATING TIMED_WAITING TERMINATED
        /* wait sleep 都会导致blocked
            功能都是线程暂停 区别：
                wait 放开手里锁去睡，
                sleep 握紧手里的锁去睡，醒了还有锁
         */

        /*
        wait : 一直等
        timed_waiting : 过时不候
         */

//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                for (int i = 0; i <=40 ; i++) {
//                    ticket.saleTicket();
//                }
//            }
//        },"A").start();  // .start 准备就绪，启动时间：等待cpu的调度启动
//
//
//
//
//
//         new Thread(new Runnable() {
//             @Override
//             public void run() {
//                 for (int i = 0; i <=40 ; i++) {
//                     ticket.saleTicket();
//                 }
//             }
//         },"B").start();
//
//          new Thread(new Runnable() {
//              @Override
//              public void run() {
//                  for (int i = 0; i <=40 ; i++) {
//                      ticket.saleTicket();
//                  }
//              }
//          },"C").start();




    }

}


class T  implements Runnable{
    @Override
    public void run() {

    }
}
